<template>
  <div class="product-list">
    <div>
      <el-button @click="toAdd" class="btn" type="primary">添加</el-button>
    </div>
    <!-- </div>  -->
    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="index" label="序号" width="180"> </el-table-column>
      <el-table-column prop="id" label="栏目编号" width="180">
      </el-table-column>
      <el-table-column prop="name" label="名称"> </el-table-column>
      <el-table-column prop="icon" label="图标">
        <template slot-scope="scope">
          <el-image
            style="width: 30px; height: 30px"
            :src="scope.row.icon"
            :preview-src-list="[scope.row.icon]"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="num" label="排序号"> </el-table-column>
      <el-table-column fixed="right" label="操作" width="100">
        <template slot-scope="scope">
          <el-button @click="handleClick(scope.row)" type="text" size="small"
            >编辑</el-button
          >
          <el-button type="text" @click="toDeleteById(scope.row.id)" size="mini"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination-div">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.page"
        :page-sizes="[2, 5, 10, 15, 20, 30]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <div>
      <el-dialog :title="title" :visible.sync="visible" @close="toClose">
        <el-form size="medium" :model="form" :rules="rules" ref="ruleForm">
          <el-form-item
            prop="name"
            label="栏目名称"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item prop="num" label="序号" :label-width="formLabelWidth">
            <el-input v-model.number="form.num" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item prop="icon" label="图标" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              :action="uploadFileURL"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="toSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { pageQuery, deleteById, saveOrUpdate } from "@/api/proCategory";
import { showFileURL, uploadFileURL } from "@/utils/config";
export default {
  data() {
    return {
      showFileURL,
      uploadFileURL,
      // 产品栏目的数据，页面一上来，就发请求，请求所有的产品栏目数据，设置到categoryData。
      categoryData: [],
      tableData: [],
      params: {
        page: 1,
        pageSize: 10,
      },
      total: 0,
      // 加载
      loading: false,
      // 模态框的显示与隐藏
      visible: false,
      // 表单数据
      form: {},
      // 表单控件标题的宽度
      formLabelWidth: "80px",
      // 模态框的标题
      title: "",
      // 图片url
      imageUrl: "",
      // 校验规则
      rules: {
        name: [
          {
            required: true,
            message: "请输入产品名称",
            trigger: "blur",
          },
        ],
        num: [
          {
            required: true,
            message: "请输入产品序号",
            trigger: "blur",
          },
          {
            type: "number",
            message: "请输入数值类型的序号",
            trigger: "blur",
          },
        ],
        icon: [
          {
            required: true,
            message: "请上传图标",
            trigger: "change",
          },
        ],
      },
    };
  },
  watch: {
    // 深度监听分页参数
    params: {
      handler() {
        this.queryCategoryData();
      },
      deep: true,
    },
  },
  computed: {},
  methods: {
    async queryCategoryData() {
      this.loading = true;
      let temp = {
        ...this.params,
        ...this.searchForm,
      };
      let res = await pageQuery(temp);
      this.tableData = res.data.list;
      this.total = res.data.total;
      this.loading = false;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.params = {
        page: 1,
        pageSize: val,
      };
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.params.page = val;
    },
    toAdd() {
      this.queryCategoryData();
      this.form = {};
      this.imageUrl = "";
      this.title = "添加产品信息";
      this.visible = true;
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.icon = showFileURL + res.data.id;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    toSave() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let res = await saveOrUpdate(this.form);
          this.$notify.success({
            title: "成功",
            message: res.message,
          });
          this.queryCategoryData();
          this.visible = false;
        } else {
          return false;
        }
      });
    },
    toClose() {
      this.$refs.ruleForm.resetFields();
    },
    handleClick(row) {
      this.queryCategoryData();
      this.form = { ...row };
      this.imageUrl = this.form.icon;
      this.title = "编辑产品信息";
      this.visible = true;
    },
    toDeleteById(id) {
      this.$confirm("此操作将永久删除该信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteById({ id });
          this.$message({ type: "success", message: res.message });
          this.queryCategoryData();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  created() {
    this.queryCategoryData();
  },
  mounted() {},
};
</script>
<style lang="scss" scoped>
.search {
  display: flex;

  .btn {
    margin-right: 10px;
  }
}
</style>